// pages/community/community.js
const http = require('../../utils/http.js');
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
     statusBarHeight: app.globalData.statusBarHeight,
    current: 'tab1',
    current1:"tab11",
    // showText:false,
    showFabu:false,
    dynamicArr:[],
    hotTopicArr:[],
    kw:'%%',
    type_id:0
  },
  openWXmap(e){
    var item=e.currentTarget.dataset.item;
    var latitude = item.address_lati/1
    var longitude = item.address_long/1
    // wx.getLocation({
    //   type: 'gcj02', //返回可以用于wx.openLocation的经纬度
    //   success:(res)=>{
    //     
    //     console.log(latitude, longitude)
        wx.openLocation({
          latitude,
          longitude,
          address: item.post_address,
          scale: 18,
          fail(err){console.log(err)}
        })
  //    }
  //  })
  },
  //
  toHot(){
    this.setData({
      current: 'tab3',
    })
    var current = this.data.current;
    var type = current == "tab1" ? 1 : current == "tab2" ? 2 : current == "tab3" ? 3 : "";
    this.getHotDynamic(1, type, this.data.kw)
  },

  toHuatiDetail(e){
    var tid=e.currentTarget.dataset.tid;
    wx.navigateTo({
      url: '/pages/topicDetail/topicDetail?tid='+tid,
    })
  },

//动态二手切换
  checkTab(e){
    var type_id=e.currentTarget.dataset.type;
    this.setData({
      type_id
    })
  },
  //图片预览
  previewImg(e){
    var imgs=e.currentTarget.dataset.imgs,
        img=e.currentTarget.dataset.img;
        console.log(imgs ,img)
    wx.previewImage({
      current: img, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },

  handleChange({ detail }) {
    this.setData({
      current: detail.key,
      // dynamicArr:[]
    });
    var type = detail.key == "tab1" ? 1 : detail.key == "tab2" ? 2 : detail.key == "tab3"?3:"";
    this.getHotDynamic(1, type);
  },

  handleChange1({ detail }) {
    this.setData({
      current1: detail.key,
      // dynamicArr:[]
    });
    // var type = detail.key == "tab1" ? 1 : detail.key == "tab2" ? 2 : detail.key == "tab3" ? 3 : "";
    // this.getHotDynamic(1, type);
  },

  showAllText(e){
    var dynamicArr = this.data.dynamicArr;
    var pid=e.currentTarget.dataset.pid;
   
    dynamicArr.some(item=>{
      if(item.pid==pid){
        item.showText=!item.showText;
        return true
      }
    })

    this.setData({
      dynamicArr
      // showText:!this.data.showText
    })
  },

  release(){
    this.setData({
      showFabu:true
    })
  },

  hidePop(){
    this.setData({
      showFabu: false
    })
  },

  //话题详情
  toTopicDetail(e){
    var tid=e.currentTarget.dataset.tid;
    wx.navigateTo({
      url: '/pages/topicDetail/topicDetail?tid='+tid,
    })
  },

 

//全部话题
  toAllTopic(){
    wx.navigateTo({
      url: "/pages/hotTopic/hotTopic",
    })
  },

  //发布动态
  releaseDynamics(){
    wx.navigateTo({
      url: "/pages/fabudongtai/fabudongtai",
    })
    this.setData({
      showFabu: false
    })
  },

  //取消分享按钮的冒泡事件
  fn(){
   // console.log(666)
  },
//点赞
  handleZan(e){
    var pid = e.currentTarget.dataset.id;
    var uid = app.globalData.uid;
    var current = this.data.current;
    var type = current == "tab1" ? 1 : current == "tab2" ? 2 : current == "tab3" ? 3 : "";
    var isZan = e.currentTarget.dataset.zan;
    if(isZan==1){
      return wx.showToast({
        title: '您已点过赞了',
        icon: 'none'
      })
      
    }
    http.fetchApi('procedure_t', { p: `R2017002|${pid}|${uid}`}).then(res=>{
      if(res.data.code==1){
        if (res.data.results[0].codes==1){
          wx.showToast({
            title: '点赞成功',
            icon:'none'
          })
          var dynamicArr = this.data.dynamicArr;
          dynamicArr.forEach(item=>{
            if(item.pid==pid){
              item.like_num++;
              item.sfdz=1;
            }
          })
          this.setData({
            dynamicArr
          })
        
        }
      }else{
        wx.showToast({
          title: '网络繁忙',
          icon: 'none'
        })
      }
    })
  },

  //评论
  handleComment(e){
    var pid = e.currentTarget.dataset.pid;
    var current = this.data.current;
    var type = current == "tab1" ? 1 : current == "tab2" ? 2 : current == "tab3" ? 3 : "";
    wx.navigateTo({
      url: "/pages/dynamicDetail/dynamicDetail?focus=" + true + '&type=' + type +'&pid='+pid,
    })
  },
  toDetails(e) {
    var pid=e.currentTarget.dataset.pid;
    var current = this.data.current;
    var type = current == "tab1" ? 1 : current == "tab2" ? 2 : current == "tab3" ? 3 : "";
    wx.navigateTo({
      url: "/pages/dynamicDetail/dynamicDetail?pid=" + pid + '&type=' + type
    })
  },

  //搜索
  inputKw(e){
    var kw ='%'+ e.detail.value+'%' || '%%'
    this.setData({
      kw
    })
  },
  confirmInput(){
    var current = this.data.current;
    var type = current == "tab1" ? 1 : current == "tab2" ? 2 : current == "tab3" ? 3 : "";
    this.getHotDynamic(1, type, this.data.kw)
  },
  //获取热门动态
  getHotDynamic(page, type, kw ='%%'){
    wx.showLoading({
      title: '加载中',
    })
    var uid = app.globalData.uid;
    var current = this.data.current;

    wx.getLocation({
      type: 'wgs84',
      success:(res)=> {
        const latitude = current=='tab2'?res.latitude:0;
        const longitude = current == 'tab2' ? res.longitude : 0;
        var params = {
          p: 'R1001009',
          k: page,
          j: 10,
          cs: `${type}|${uid}|${kw}|${longitude}|${latitude}`
        }
        http.fetchApi('procedureList', params).then(ret=>{
         wx.hideLoading();
          var { code, results } = ret.data;
         // console.log(code, results)
          if(code==1){
            var dynamicArr = this.data.dynamicArr;
            var dynamicArr1 = results;
            if(page==1){
              dynamicArr = results;
            }else{
              dynamicArr = [...dynamicArr, ...dynamicArr1]
            }
            dynamicArr.forEach(item=>{
              item.showText=false
            })
            this.setData({
              dynamicArr,
              page,
              pageNum: dynamicArr1.length
            })
          }
        })
      }
    })
    
  },

  //获取热门话题
  getHotTopic(){
    http.fetchApi('procedure_t', { p: `R2019006`}).then(res=>{
      if(res.data.code==1){
        var hotTopicArr = res.data.results;
        this.setData({
          hotTopicArr
        })
      }
    })
  },
  fn1(){},

  //个人信息中心
  toHomepage(e){
    var eid=e.currentTarget.dataset.eid;
    wx.navigateTo({
      url: '/pages/toPersonal/toPersonal?eid='+eid
    })
  },

  emoji2Str(str) {

    return unescape(escape(str).replace(/\%uD.{3}/g, ''));

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(app.globalData.statusBarHeight)
    // 分享进来时获取uid
    if (app.globalData.uid) {
      this.getHotDynamic(1, 1);
      this.getHotTopic();
    } else {
      wx.getSetting({
        success: (res) => {
          if (!res.authSetting['scope.userInfo']) {
            wx.showModal({
              title: '提示',
              content: '您还没有授权,请开启授权',
              confirmColor: '#0DCF92',
              success(ret) {
                if (ret.confirm) {
                  wx.reLaunch({
                    url: '/pages/index/index',
                  })
                } else if (ret.cancel) {

                }
              }
            })

          } else {
            wx.getUserInfo({
              success: results => {
                app.globalData.userInfo = results.userInfo
                console.log(app.globalData.userInfo);

                wx.login({
                  success: (res2) => {

                    if (res2.code) {
                      var url;
                      const yxhj = wx.getSystemInfoSync();
                      console.log(yxhj.AppPlatform)
                      app.globalData.cj = yxhj.AppPlatform
                      if (yxhj.AppPlatform == 'qq') {
                        url = app.globalData.host + 'qqApi/login'
                      } else {
                        url = app.globalData.host + 'api/login'
                      }
                      wx.request({
                        url,
                        method: 'get',
                        header: {
                          "Content-Type": "applciation/json"
                        },
                        // data: { encryptedData: results.encryptedData, iv: results.iv, code: res.code },
                        data: { avatarUrl: results.userInfo.avatarUrl, nickName: this.emoji2Str(results.userInfo.nickName), code: res2.code },
                        success: (result) => {
                          if (result.data.code == 1) {

                            app.globalData.token = result.data.accesstoken;
                            //uid保存全局
                            app.globalData.uid = result.data.uid;
                            this.getHotDynamic(1, 1);
                            this.getHotTopic();
                          } else {
                            wx.showToast({
                              title: '网络繁忙',
                              icon: 'none'
                            })

                          }

                        }
                      })


                    } else {
                      console.log('网络繁忙' + res.errMsg)
                    }
                  }
                })

              }
            })
          }
        }
      })
    }
    
    // this.getHotDynamic(1,1);
    // this.getHotTopic();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // var query = wx.createSelectorQuery();
    // setTimeout(()=>{
    //   query.select('.dynamics-text').boundingClientRect();
    // },1000)
    // console.log(query.select('.dynamics-text'))
    // query.exec((res) => {
    //   console.log(res)
    //   res[0].height;
    //   console.log("height==", res[0].height)
    //   var height = res[0].height;
    //   //20为css里设置的view的line-height
    //   this.data.colNum = height / 20;
    //   console.log("行数==", this.data.colNum)
    //   if (height>60){
    //     this.setData({
    //       colNum: this.data.colNum,
    //       showText:false
    //     })
    //     return
    //   }
    //   this.setData({
    //     colNum: this.data.colNum,
    //   })
    // })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
   
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var current = this.data.current;
    var type = current == "tab1" ? 1 : current == "tab2" ? 2 : current == "tab3" ? 3 : "";
    var page = this.data.page || 1;
    page++;
    if (this.data.pageNum<10){
      http.showToast('暂无更多!' + '', '', 'none')
      return
    }
    this.getHotDynamic(page,type);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    console.log(res)
    var uid = app.globalData.uid;
    var current = this.data.current;
    var type = current == "tab1" ? 1 : current == "tab2" ? 2 : current == "tab3" ? 3 : "";
    if (res.from === 'button') {
      // 来自页面内转发按钮
      var pid = res.target.dataset.id;
      http.fetchApi('procedure_t', { p: `R2017005|${pid}|${uid}` }).then(req=>{
        if(req.data.code==1){
          if (req.data.results[0].codes==1){
            var dynamicArr = this.data.dynamicArr;
            dynamicArr.forEach(item => {
              if (item.pid == pid) {
                item.fenxiang_num++;
              
              }
            })
            this.setData({
              dynamicArr
            })
          }
        }
      })

      return {
        // title: '自定义转发标题',
        path: '/pages/dynamicDetail/dynamicDetail?pid=' + pid + '&type' + type + '&shared=1'
      }
    }
   
  }
})